import createG2 from 'g2-react';
import { Stat } from 'g2';
import React from 'react';
import ReactDOM from 'react-dom';
import Logger from '../../../../utils/Logger';

const logger = Logger.getLogger('PieChart');

//声明一个Chart
const Chart = createG2(chart => { 
      // 重要：绘制饼图时，必须声明 theta 坐标系
      chart.coord('theta', {
        radius: 0.5 // 设置饼图的大小 
      });

      chart.tooltip({
        title: "测试饼图",
        map: {
          value: 'value'
        }
      });
      //所有图例都不显示
      chart.legend(false);

      chart.intervalStack()
        .position(Stat.summary.percent('value'))
        .color('name')
        .label('name*..percent',function(name, percent){
          percent = (percent * 100).toFixed(2) + '%';
          return name + ' ' + percent;
        });
      chart.render();
      // 设置默认选中
      var geom = chart.getGeoms()[0]; // 获取所有的图形
      var items = geom.getData(); // 获取图形对应的数据
      geom.setSelected(items[1]); // 设置选中      
    });

/**
 * 饼图组件
 */
class PieChart extends React.Component {

  constructor(props) {
    super(props);
    this.initLineData();
  }

  state = {
      width: 520,
      height: 459,
      plotCfg: {
        margin: [50, 100, 90, 120],
      },
      forceFit: true, //自适应
      data:[],
  };

  // 在react router中切换时, 组件不会重新mount, 只有props会变化
  componentWillReceiveProps = (nextProps) => {
    this.initLineData();
  }
  /**
   *  初始化数据
   */
  initLineData(){
    var temData=[];
    for(var i=0;i<this.props.userData.length;i++){
            var tmp={};
            tmp.name=this.props.userData[i].timeStr;
            tmp.value=this.props.userData[i].proportion;
            temData.push(tmp);
    }
    this.setState({data:temData});
  }

  render() {
    return (
        <Chart
            data={this.state.data}
            width={this.state.width}
            height={this.state.height}
            forceFit={this.state.forceFit} 
        />
    );
  }

}
export default PieChart;